package org.leon;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkClientDemo {

    private static ZkClient zkClient;

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        // 连接 zk 的过程是同步的, 和原生 api 的异步连接不一样
        zkClient = new ZkClient("127.0.0.1:2181");

        zkClient.writeData("/dynamic-db/db-node", "jdbc:mysql://localhost:3306/wps_translate?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC,root,localadmin");

        /*subscribeSubNode();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    /*
        zkClient 为创建不同类型的节点提供了快捷方法, 如 zkClient.createEphemeral(String path)
    */
    private static void createNode() {
        // 级联创建, 可以使用此方法可以递归的创建的节点
        zkClient.createPersistent("/zkclient/node1", true);
    }

    private static void delete() {
        /*
        *  除了普通的删除方法, zkClient 还提供了一个递归删除的方法
        * */
        // zkClient.delete(path)
        zkClient.deleteRecursive("/cunzheng");
    }

    private static void getChildren() {
        List<String> children = zkClient.getChildren("/zkclient");
        System.out.println(children);
    }

    private static void subscribeSubNode() {
        /*
        *  监听子节点的变化, 注意: zkclient 甚至可以把监听注册到不存在的节点上, 而且触发监听事件后, zkclient 会自动再次绑定监听
        */
        /*
        *  s : 当前节点 path
        *  list : 子节点列表
        */
        zkClient.subscribeChildChanges("/laogu", (s, list) -> {
            System.out.println("root path" + s);
            System.out.print("children: ");
            System.out.println(list);
        });
    }

    private static void getData() {
        String path = "/lagou-ephemeral";
        boolean exists = zkClient.exists(path);
        if (!exists) {
            zkClient.createEphemeral(path);
        }
        // 注册监听
        zkClient.subscribeDataChanges(path, new IZkDataListener(){

            /*  当前节点数据变化后触发
            *  s : 绑定的节点的 path
            *  o : 变化后的节点的值
            */
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            /*
                删除当前节点时触发
            *  s : 绑定监听的 path
            */
            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });

        // 节点写入值
        zkClient.writeData(path, 123456);

    }

}
